import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';

import 'dart:async';

import 'package:t3_data_service/data_provider/map_sctx/t3_map_sctx_provider.dart';
import 'package:t3_map/t3_map_plugin/t3_flutter_map.dart';
import 'package:t3_assets/t3_assets_name.dart';


void main() {
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {

  late final T3MapWidget mapWidget;
  late final T3MapController controller;

  T3Polyline? polyline;

  List<T3Annotation>? annotations;

  int placeholder = 0;

  @override
  void initState() {
    super.initState();
    controller = T3MapController();
    mapWidget = T3MapWidget(
                            mapType: T3MapType.amap, 
                            controller: controller, 
                            initialCameraPosition: const T3MapCameraPosition(centerCoordinate: T3LocationCoordinate2D(longitude: 118.811221, latitude: 31.911858)));
    
    controller.eventStream.onMapInitCompleted().listen((event) {
      debugPrint('onMapInitCompleted1');
    });

    controller.eventStream.regionWillChange().listen((event) {
      debugPrint('regionWillChange, ${event.value.toString()}');
    });

    controller.eventStream.regionChanged().listen((event) {
      debugPrint("regionChanged，zoomLevel: ${event.value.zoomLevel}, centerCoordinate: ${event.value.centerCoordinate.toString()}");
    });

    controller.eventStream.regionDidChange().listen((event) {
      debugPrint('regionDidChange, ${event.value.toString()}');
    });

    controller.eventStream.polylineDidTap().listen((event) {
      debugPrint('polylineDidTap, ${event.value.toString()}');
    });

    controller.eventStream.annotationDidTap().listen((event) {
      debugPrint('annotationDidTap, ${event.value.toString()}');
    });
  }

  // Platform messages are asynchronous, so we initialize in an async method.
  Future<void> initPlatformState() async {

  }

  @override
  Widget build(BuildContext context) {

    List<Widget> children = [];

    children.add(const Text('测试platform map view'));

    for (var i = 0; i < placeholder; i++) {
      children.add(const Text('测试placeholder'));
    }

    children.addAll( [
              const Text('测试platform map view'),
              Wrap(
                spacing: 8,
                children: [
                 ElevatedButton(
                onPressed: addPolylineButtonDidClicked, 
                child: const Text('添加polyline')
              ),
              ElevatedButton(
                onPressed: updatePolylineButtonDidClicked, 
                child: const Text('更新polyline')
              ),
              ElevatedButton(
                onPressed: showPolylineButtonDidClicked, 
                child: const Text('可视区域内显示polyline')
              ),
              ElevatedButton(
                onPressed: removePolylineButtonDidClicked, 
                child: const Text('移除polyline')
              ),
              ElevatedButton(
                onPressed: setupShowsUserLocatioButtonDidClicked, 
                child: const Text('设置显示用户位置')
              ),
              ElevatedButton(
                onPressed: userLocatioIsVisibleButtonDidClicked, 
                child: const Text('用户位置是否可见')
              ),
              ElevatedButton(
                onPressed: userTrackingModeButtonDidClicked, 
                child: const Text('设置定位模式为跟随模式')
              ),
              ElevatedButton(
                onPressed: setupCenterButtonDidClicked, 
                child: const Text('设置中心点在百家湖')
              ),
              ElevatedButton(
                onPressed: setupCenter1ButtonDidClicked, 
                child: const Text('设置中心点在南京南站(无动画)')
              ),
              ElevatedButton(
                onPressed: setupZoom15ButtonDidClicked, 
                child: const Text('设置地图缩放级别15（无动画）')
              ),
              ElevatedButton(
                onPressed: setupZoom17ButtonDidClicked, 
                child: const Text('设置地图缩放级别17')
              ),
              ElevatedButton(
                onPressed: setupPinAnnotationButtonDidClicked, 
                child: const Text('添加地图起点大头针')
              ),
              ElevatedButton(
                onPressed: showPinAnnotationButtonDidClicked, 
                child: const Text('展示地图起点大头针')
              ),
              ElevatedButton(
                onPressed: removePinAnnotationButtonDidClicked, 
                child: const Text('移除地图起点大头针')
              ),
              ElevatedButton(
                onPressed: showPolylineAndPinAnnotationButtonDidClicked, 
                child: const Text('同时显示地图上的线段和大头针')
              ),
              ElevatedButton(
                onPressed: setupScreenAnchor, 
                child: const Text('设置地图锚点')
              )
              ]),              
            ]);

    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Plugin example app'),
        ),
        body: Center(
          child: Column(
            children: [
              SizedBox(
                width: 300,
                height: 200,
                child: mapWidget
              ),
              SingleChildScrollView(
                child: Center(
                  child: Column(
                    children: children,
                  ),
                ),
              )
            ]
          )
        ),
      ),
    );
  }

  void addPolylineButtonDidClicked() {

    const origin = T3LocationCoordinate2D(longitude: 118.798039, latitude: 31.96875);
    const destination = T3LocationCoordinate2D(longitude: 118.797499, latitude: 32.087104);
    
    // 绘制大头针
    
    T3AnnotationOptions originBubbleOptions = T3AnnotationOptions.fromBubble(
                                                                              coordinate: origin, 
                                                                              zIndex: 1, 
                                                                              bubble: T3BubbleAnnotationOptions.valuation(
                                                                                addressTextOption: T3TextOption(
                                                                                  text: "天安门广场", 
                                                                                  normalStyle: T3TextStyle(color: "#1d2232", fontSize: 10, fontWeight: T3FontWeight.medium)),
                                                                                timeTextOption: T3TextOption(
                                                                                  text: "12分钟", 
                                                                                  normalStyle: T3TextStyle(color: "#00AD59", fontSize: 14, fontWeight: T3FontWeight.bold)),
                                                                                timeTipsTextOption: T3TextOption(
                                                                                  text: "最快上车", 
                                                                                  normalStyle: T3TextStyle(color: "#A5A7AD", fontSize: 10, fontWeight: T3FontWeight.regular)),
                                                                                // stopInfoTextOption: T3TextOption(
                                                                                //   text: "此处限停12分钟", 
                                                                                //   normalStyle: T3TextStyle(color: "#FA6400", fontSize: 8, fontWeight: T3FontWeight.regular)),
                                                                                imageOption: T3ImageOption(imageName: T3AssetsName.map_icon_start_pin.value, width: 28, height: 28))
                                                                                );

    T3AnnotationOptions destinationBubbleOptions = T3AnnotationOptions.fromBubble(
                                                                              coordinate: destination, 
                                                                              zIndex: 1, 
                                                                              bubble: T3BubbleAnnotationOptions.valuation(
                                                                                addressTextOption: T3TextOption(
                                                                                  text: "天安门广场", 
                                                                                  normalStyle: T3TextStyle(color: "#1d2232", fontSize: 10, fontWeight: T3FontWeight.medium)),
                                                                                // timeTextOption: T3TextOption(
                                                                                //   text: "10:51", 
                                                                                //   normalStyle: T3TextStyle(color: "#FA6400", fontSize: 14, fontWeight: T3FontWeight.bold)),
                                                                                // timeTipsTextOption: T3TextOption(
                                                                                //   text: "预计到达", 
                                                                                //   normalStyle: T3TextStyle(color: "#A5A7AD", fontSize: 10, fontWeight: T3FontWeight.regular)),
                                                                                imageOption: T3ImageOption(imageName: T3AssetsName.map_icon_end_pin.value, width: 28, height: 28))
                                                                                );
    
  

    annotations = controller.addAnnotations([originBubbleOptions, destinationBubbleOptions]);

    controller.showAnnotations(annotations: controller.annotations, animated: true);
    
    // 计算路线
    final future = T3RouteManager.getDrivingRouteUnionEndPointRecommend(
                                mapType: T3MapType.amap, 
                                origin: origin,
                                arriveOrigin: null,
                                destination: destination,
                                arriveDestination: null,
                                viaPoints: null,
                                originPoiId: null,
                                destPoiId: 'cd27b7d620ffa0f',
                                areaCode: null,//'320115',
                                departureTime: null
                                );

    future.then((value) {
      debugPrint("getWalkRoute : ${value.toString()}");

      if (value != null) {
        List<T3Polyline> polylineList = [];
        var isFirst = true;
        for (var element in value.routeResult.routes) {
          final style = T3MultiPolylineStyle(
            width: 7, 
            lineDashType: T3PolylineDashStyle.dot, 
            lineJoinType: T3PolylineJoinStyle.round, 
            miterLimit: 20, 
            isSelected: isFirst ? true : false, 
            traffic: element.traffic, 
            fillColorValue: '#A5A7AD', 
            strokeColorValue: '#A5A7AD');

          final options = T3PolylineOptions(points: element.coordinates, routeID: element.routeId, style: style);
          final polyline = controller.addPolyline(options: options);
          polylineList.add(polyline);
          isFirst = false;
        }

        controller.showPolylines(polylines: polylineList, animated: true);
      }
    });


  }

  void updatePolylineButtonDidClicked() {

    const List<T3LocationCoordinate2D> points = [
      T3LocationCoordinate2D(longitude: 116.359406, latitude: 39.910612),
      T3LocationCoordinate2D(longitude: 116.345948, latitude: 39.910298),
      T3LocationCoordinate2D(longitude: 116.361775, latitude: 39.912964),
      T3LocationCoordinate2D(longitude: 116.366478, latitude: 39.913435),
      T3LocationCoordinate2D(longitude: 116.424897, latitude: 39.916258),
      T3LocationCoordinate2D(longitude: 116.417165, latitude: 39.91367),
    ];

    const T3PolylineStyle style = T3PolylineStyle(width: 10, fillColorValue: '#fcba03', strokeColorValue: '#fcba03');

    final options = T3PolylineOptions(points: points, style: style);

    if (polyline != null) {
      controller.updatePolyline(polyline: polyline!, newPolylineOptions: options);
    }
  }

  void showPolylineButtonDidClicked() {
    if (polyline != null) {
      controller.showPolylines(polylines: [polyline!], edgeInsets: const EdgeInsets.all(5), animated: true);
    }
  }

  void removePolylineButtonDidClicked() {
    if (polyline != null) {
      controller.removePolyline(polyline: polyline!);  
    }
  }

  void setupShowsUserLocatioButtonDidClicked() {
    controller.showsUserLocation = !controller.showsUserLocation;
  }

  Future<void> userLocatioIsVisibleButtonDidClicked() async {
    final visible = await controller.userLocationVisible;
    // debugPrint("adfadf: $visible");
    final msg = visible ? "可见" : "可不见";
    Fluttertoast.showToast(
      msg: '用户位置: $msg',
      toastLength: Toast.LENGTH_SHORT,
      gravity: ToastGravity.BOTTOM,
      timeInSecForIosWeb: 1,
      backgroundColor: Colors.black,
      textColor: Colors.white,
      fontSize: 16.0,
    );
  }

  void userTrackingModeButtonDidClicked() {
    controller.setupUserTrackingMode(T3UserTrackingMode.follow, animated: true);
  }

  void setupCenterButtonDidClicked() {
    controller.setupMapViewCenter(coordinate: const T3LocationCoordinate2D(longitude: 118.819984, latitude: 31.930099), animated: true);
  }
  
  void setupCenter1ButtonDidClicked() {
    controller.setupMapViewCenter(coordinate: const T3LocationCoordinate2D(longitude: 118.797984, latitude: 31.968827), animated: false);
  } 


  void setupZoom15ButtonDidClicked() {
    controller.setupMapViewZoomLevel(level: 15, animated: false);
  }

  void setupZoom17ButtonDidClicked() {
    controller.setupMapViewZoomLevel(level: 17, animated: true);
  }

  void setupPinAnnotationButtonDidClicked() {
    T3AnnotationOptions options = T3AnnotationOptions.fromPin(
      coordinate: const T3LocationCoordinate2D(longitude: 116.241048, latitude: 39.970377), 
      zIndex: 1, 
      pin: T3PinAnnotationOptions.start(addressText: "天安门广场"));

      T3AnnotationOptions options1 = T3AnnotationOptions.fromPin(
      coordinate: const T3LocationCoordinate2D(longitude: 116.525403, latitude: 39.947892), 
      zIndex: 1, 
      pin: T3PinAnnotationOptions.start(addressText: "王府井广场府井广场王府井广场府井广场王府井广场府井广场"));

      T3AnnotationOptions options2 = T3AnnotationOptions.fromPin(
      coordinate: const T3LocationCoordinate2D(longitude: 116.379682, latitude: 39.868527), 
      zIndex: 1, 
      pin: T3PinAnnotationOptions.start(addressText: null));


    annotations = controller.addAnnotations([options,options1,options2]);

    controller.showAnnotations(annotations: controller.annotations, animated: true);
  }

  void showPinAnnotationButtonDidClicked() {
    controller.showAnnotations(annotations: controller.annotations, animated: true);
  }

  void removePinAnnotationButtonDidClicked() {
    controller.removeAnnotations(controller.annotations);
  }

  void showPolylineAndPinAnnotationButtonDidClicked() {
     controller.showPolylinesAndAnnotations(polylines: controller.polylines, annotations: controller.annotations, edgeInsets: const EdgeInsets.all(0),animated: true);
  }

  void setupScreenAnchor() {
    controller.screenAnchor = const Offset(0.25, 0.25);
  }
}
